package com.longcai.cm.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.longcai.cm.base.aop.Log;
import com.longcai.cm.base.bean.PageVo;
import com.longcai.cm.base.bean.Pageable;
import com.longcai.cm.bean.R;
import com.longcai.cm.common.utils.RequestUtil;
import com.longcai.cm.delay.SecKillGoodDelay;
import com.longcai.cm.domain.JaGoodsCoupon;
import com.longcai.cm.domain.JaGoodsInfo;
import com.longcai.cm.domain.JaOrder;
import com.longcai.cm.domain.VMemberVipList;
import com.longcai.cm.domain.back.vm.HomeStatistic;
import com.longcai.cm.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.DelayQueue;

/**
 * @author LBX
 * @date 2024-08-02
 */
@RestController
@RequestMapping("/JaGoodsInfo")
public class JaGoodsInfoController {

    @Resource
    private JaGoodsInfoService jaGoodsInfoService;

    @Resource
    private DelayQueue<SecKillGoodDelay> secKillGoodDelayQueue;

    @Resource
    private FaMemberService memberService;

    @Resource
    private VMemberVipListService memberVipListService;

    @Resource
    private JaOrderService orderService;

    @Resource
    private JaShopService shopService;

    @Resource
    private JaGoodsCouponService goodsCouponService;

    @RequestMapping("/statistic")
    public R<HomeStatistic> homeStatistic() {
        final List<JaOrder> list = orderService.lambdaQuery().select(JaOrder::getPayAmount, JaOrder::getOrderProfit).between(JaOrder::getOrderStatus,1,3).list();
        final List<JaGoodsInfo> goodList = jaGoodsInfoService.lambdaQuery().select(JaGoodsInfo::getSaleCount,JaGoodsInfo::getType).list();
        final List<JaGoodsCoupon> couponsList = goodsCouponService.lambdaQuery().select(JaGoodsCoupon::getSaleCount).list();
        HomeStatistic statistic = new HomeStatistic(
                memberService.count(),
                memberVipListService.lambdaQuery().gt(VMemberVipList::getExpireTime, DateUtil.now()).count(),
                orderService.count(),
                BigDecimal.valueOf(list.size() > 0 ? list.stream().mapToDouble(m -> m.getPayAmount().doubleValue()).sum() : 0) ,
                BigDecimal.valueOf(list.size() > 0 ? list.stream().mapToDouble(m -> m.getOrderProfit().doubleValue()).sum() : 0),
                shopService.count(),
                goodList.size() > 0 ? goodList.stream().filter(f -> f.getType() == 1).mapToLong(JaGoodsInfo::getSaleCount).sum() : 0,
                couponsList.size() > 0 ? couponsList.stream().mapToLong(JaGoodsCoupon::getSaleCount).sum() : 0,
                goodList.size() > 0 ? goodList.stream().filter(f -> f.getType() == 2).mapToLong(JaGoodsInfo::getSaleCount).sum() : 0
        );
        return R.success(statistic);
    }

    @RequestMapping("/getList")
    public R<PageVo<JaGoodsInfo>> getList(HttpServletRequest request) {
        Pageable pageInfo = RequestUtil.getPageable(request);
        PageVo<JaGoodsInfo> result = jaGoodsInfoService.getPageBean(pageInfo, JaGoodsInfo.class);
        return R.success(result);
    }

    /**
     * @param vo 插入实体
     * @return R
     */
    @Log
    @RequestMapping("/save")
    public R<String> save(JaGoodsInfo vo) {
        boolean success;
        if (StringUtils.isNotBlank(vo.getId())) {
            success = jaGoodsInfoService.updateById(vo);
            secKillGoodDelayQueue.removeIf(s -> s.getGoodId().equals(vo.getId()));
        } else {
            success = jaGoodsInfoService.save(vo);
        }
        if (StringUtils.isNotBlank(vo.getExpireTime())) {
            final DateTime expireTime = DateUtil.parse(vo.getExpireTime());
            final long leftTime = DateUtil.between(DateUtil.date(), expireTime, DateUnit.SECOND);
            secKillGoodDelayQueue.add(new SecKillGoodDelay(vo.getId(), leftTime));
        }
        return success ? R.success() : R.error();
    }

    /**
     * @param vo      修改实体
     * @param request id
     * @return R
     */
    @Log
    @RequestMapping("/edit")
    public R<String> edit(JaGoodsInfo vo, HttpServletRequest request) {
        String id = request.getParameter("id");
        if (StringUtils.isNotBlank(id)) {
            boolean success = jaGoodsInfoService.updateById(vo);
            return success ? R.success() : R.error();
        } else {
            return R.error("id不能为空");
        }
    }

    /**
     * @param id 主键
     * @return R
     */
    @Log
    @RequestMapping("/delete/{id}")
    public R<String> deleteByPrimaryKey(@PathVariable("id") Integer id) {
        final boolean success = jaGoodsInfoService.removeById(id);
        return success ? R.success() : R.error();
    }

    /**
     * 【API】----  删除多个数据
     *
     * @return R
     */
    @Log
    @RequestMapping("/delete")
    public R<String> delete(String ids) {
        String[] idStrings = ids.split(",");
        for (String idString : idStrings) {
            final boolean success = jaGoodsInfoService.removeById(idString);
            if (!success) {
                return R.error();
            }
        }
        return R.success();
    }
}
